﻿#include "genealogy.h"
#include "ui_genealogy.h"



Genealogy::Genealogy(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Genealogy)
{
    ui->setupUi(this);
    this->setAutoFillBackground(true);
    this->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowMinimizeButtonHint|Qt::WindowMaximizeButtonHint);
    initWidget();
    initAnim();
    initConnections();

    //导入主题配置
    int tmp = 0;
    QFile file(QApplication::applicationDirPath()+"/theme");
    if(file.open(QIODevice::ReadWrite | QIODevice::Text)){
        QTextStream stream(&file);
        tmp = QString(stream.readLine()).toInt();
    }
    file.close();
    updateTheme(tmp);
    menuBar->setThemeIndex(tmp);

    this->window()->setWindowTitle("家谱管理器");
    isFileOpening = false;
}

Genealogy::~Genealogy()
{
    delete ui;
}

//初始化connect
void Genealogy::initConnections(){

    //工具界面关闭按钮
    connect(toolWidget, &ToolWidget::closeToolArea, this, &Genealogy::closeToolAreaAnima);

    //过渡动画相关
    connect(paraAnimGroup1, &QParallelAnimationGroup::finished, toolWidget, &ToolWidget::hide);
    connect(scaleAnimation2, &QPropertyAnimation::finished, [this]{
        toolWidget->show();
    });
    connect(posAnimation2, &QPropertyAnimation::finished, [this]{
        posAnimation3->setStartValue(toolWidget->pos());
        posAnimation3->setEndValue(toolWidget->pos()-QPoint(310,0));
        posAnimation3->start();
        toolWidget->setCurrentIndex(pageType);
    });


    //菜单栏相关
    connect(menuBar, &MenuBar::changeTheme, this, &Genealogy::updateTheme);
    connect(menuBar, &MenuBar::changeDisplayType, [this](int index){
        displayWidget->setCurrentIndex(index);
    });
    connect(menuBar, &MenuBar::openFileDialog, this, &Genealogy::openFile);
    connect(menuBar, &MenuBar::newFileDialog, this, &Genealogy::newFile);
    connect(menuBar, &MenuBar::closeCurFile, this, &Genealogy::closeFile);
    connect(menuBar, &MenuBar::showState, [this]{
        toolWidget->refreshState();
        showToolAreaAnima(3);
    });
    connect(menuBar, &MenuBar::showSearch, [this]{
        showToolAreaAnima(0);
    });

    //右键菜单相关
    //打开详情
    connect(toItemDetailAction, &QAction::triggered, [this](){
        toolWidget->isAddingNew = false;
        toolWidget->processID = ID->text().toInt();
        toolWidget->clearDTPage();
        toolWidget->readValueFromData();
        showToolAreaAnima(2);
    });
    //新增子女
    connect(newItemAsChildAction, &QAction::triggered, [this]{
        toolWidget->isAddingNew = true, toolWidget->isAddingChild = true;
        toolWidget->processID = ID->text().toInt();
        toolWidget->clearDTPage();
        showToolAreaAnima(2);
    });
    //新增伴侣
    connect(newItemAsMateAction, &QAction::triggered, [this]{
        toolWidget->isAddingNew = true, toolWidget->isAddingChild = false;
        toolWidget->processID = ID->text().toInt();
        toolWidget->clearDTPage();
        toolWidget->disableManChoice();
        showToolAreaAnima(2);
    });
    //删除
    connect(deleteItemAction, &QAction::triggered, [this]{
        int id = ID->text().toInt();
        displayWidget->deleteValue(id);
        if(toolWidget->processID == id){
            closeToolAreaAnima();
        }
    });

    //增加祖先
    connect(displayWidget, &DisplayWidget::addAncestry, [this]{
        toolWidget->isAddingAncestry = true;
        toolWidget->disableWomanChoice();
        toolWidget->clearDTPage();
        toolWidget->disableDel();
        showToolAreaAnima(2);
    });

    //增加祖先后，初始树
    connect(toolWidget, &ToolWidget::addedAncestry, [this]{
        displayWidget->setCurrentIndex(0);
        displayWidget->inputDataToTreeWidget();
        displayWidget->inputDataToTableWidget();
        menuBar->enableDisplayMenu();
    });

    //从表格到详情页面
    connect(displayWidget, &DisplayWidget::toDetail, [this](int id){
        toolWidget->isAddingNew = false;
        toolWidget->processID = id;
        toolWidget->clearDTPage();
        toolWidget->readValueFromData();
        showToolAreaAnima(2);
    });

    //从信息搜索的表格到详情页面
    connect(toolWidget, &ToolWidget::fromKWSearchToDetail, [this](int id){
        toolWidget->isAddingNew = false;
        toolWidget->processID = id;
        toolWidget->clearDTPage();
        toolWidget->readValueFromData();
        toolWidget->showReturnButton();
        showToolAreaAnima(2);
    });

    //表格的右键菜单的亲戚查询按下
    connect(displayWidget, &DisplayWidget::toRelSearch, [this](int id){
        toolWidget->setRLSearchID(id);
        showToolAreaAnima(1);
    });

    //关闭工具页面
    connect(displayWidget, &DisplayWidget::closeTool, this, &Genealogy::closeToolAreaAnima);

    //当工具控件返回按钮被点击，返回到之前的工具控件页面
    connect(toolWidget, &ToolWidget::retrunToPrevPage, this, &Genealogy::showToolAreaAnima);


    //在工具控件对信息修改后，更新显示信息的页面
    connect(toolWidget, &ToolWidget::addedChild, displayWidget, &DisplayWidget::addChild);
    connect(toolWidget, &ToolWidget::updateValue, displayWidget, &DisplayWidget::updateValue);
    connect(toolWidget, &ToolWidget::addedMate, displayWidget, &DisplayWidget::addMate);
    connect(toolWidget, &ToolWidget::deleteValue, displayWidget, &DisplayWidget::deleteValue);

    //关闭显示菜单选项
    connect(displayWidget, &DisplayWidget::disableMenu, menuBar, &MenuBar::disableDisplayMenu);

}

//UI控件的初始化
void Genealogy::initWidget(){
    //初始化右键菜单
    itemMenu = new QMenu(this);
    itemMenu->setToolTipsVisible(false);
    toItemDetailAction = new QAction("详细信息", this);
    deleteItemAction = new QAction("删除此项", this);
    newItemAsChildAction = new QAction("增加子女", this);
    newItemAsMateAction = new QAction("增加伴侣", this);

    //利用右键菜单的最后一项的text属性传递
    //要处理的id，设置此项为不可见
    ID = new QAction("",this);
    ID->setVisible(false);

    itemMenu->addAction(toItemDetailAction);
    itemMenu->addAction(deleteItemAction);
    itemMenu->addAction(newItemAsChildAction);
    itemMenu->addAction(newItemAsMateAction);
    itemMenu->addAction(ID);

    //添加主题颜色代码
    themeColors.append(QColor(22, 97, 171));//靛青
    themeColors.append(QColor(192, 72, 81));//玉红
    themeColors.append(QColor(43, 174, 133));//铜绿
    themeColors.append(QColor(249, 125, 28));//橘橙
    themeColors.append(QColor(15, 20, 35));//钢蓝
    themeColors.append(QColor(126, 22, 113));//魏紫
    themeColors.append(QColor(226, 192, 39));//姜黄
    themeColors.append(QColor(134, 126, 128));//瓦灰
    themeColors.append(QColor(240, 173, 160));//桃粉
    themeColors.append(QColor(188, 159, 119));//茶白

    //设置标题名称
    titleBar = new TitleBar(this, "家谱管理器");
    titleBar->show();

    menuBar = new MenuBar(this);
    menuBar->show();

    toolWidget = new ToolWidget(&treeData, this);
    toolWidget->show();
    toolWidget->hide();

    displayWidget = new DisplayWidget(&treeData,itemMenu, this);
    displayWidget->show();

    //设置布局为栅格布局
    QGridLayout *gLayout = new QGridLayout();
    gLayout->addWidget(titleBar);
    gLayout->setSpacing(0);
    gLayout->setContentsMargins(2, 2, 2, 2);
    setLayout(gLayout);

    gLayout->addWidget(titleBar, 0, 0, 1, 2);
    gLayout->addWidget(menuBar, 1, 0, 1, 2);
    gLayout->addWidget(displayWidget, 2, 0, 1, 1);
    gLayout->addWidget(toolWidget, 2, 1, 1 ,1);

    pageType = 0;
    isFileOpening = false;
    themeIndex = 0;
}

//初始化过渡动画
void Genealogy::initAnim(){

    posAnimation1 = new QPropertyAnimation(toolWidget, "pos");
    posAnimation1->setEasingCurve(QEasingCurve::InOutQuart);
    posAnimation1->setDuration(200);

    scaleAnimation1 = new QPropertyAnimation(displayWidget, "size");
    scaleAnimation1->setEasingCurve(QEasingCurve::InOutQuart);
    scaleAnimation1->setDuration(200);

    paraAnimGroup1 = new QParallelAnimationGroup(this);
    paraAnimGroup1->addAnimation(posAnimation1);
    paraAnimGroup1->addAnimation(scaleAnimation1);

    posAnimation2 = new QPropertyAnimation(toolWidget, "pos");
    posAnimation2->setEasingCurve(QEasingCurve::InOutQuart);
    posAnimation2->setDuration(200);

    posAnimation3 = new QPropertyAnimation(toolWidget, "pos");
    posAnimation3->setEasingCurve(QEasingCurve::InOutQuart);
    posAnimation3->setDuration(200);

    scaleAnimation2 = new QPropertyAnimation(displayWidget, "size");
    scaleAnimation2->setEasingCurve(QEasingCurve::InOutQuart);
    scaleAnimation2->setDuration(200);
}

//打开工作栏区域的动画
void Genealogy::showToolAreaAnima(int type){
    pageType = type;
    if(!toolWidget->isHidden()&&toolWidget->currentIndex() == pageType&&pageType!=2) return;
    if(toolWidget->isHidden()){
        toolWidget->setCurrentIndex(pageType);
        scaleAnimation2->setStartValue(displayWidget->size());
        scaleAnimation2->setEndValue(displayWidget->size()-QSize(300,0));
        scaleAnimation2->start();

    }
    else{
        posAnimation2->setStartValue(toolWidget->pos());
        posAnimation2->setEndValue(toolWidget->pos()+QPoint(310,0));
        posAnimation2->start();
    }
}

//关闭工作栏区域的动画
void Genealogy::closeToolAreaAnima(){
    if(!toolWidget->isHidden()){
        posAnimation1->setStartValue(toolWidget->pos());
        posAnimation1->setEndValue(toolWidget->pos()+QPoint(300,0));

        scaleAnimation1->setStartValue(displayWidget->size());
        scaleAnimation1->setEndValue(displayWidget->size()+QSize(300,0));

        paraAnimGroup1->start();
    }
}

//调用winapi缩放窗口大小，参考fengMisaka https://tinyurl.com/w89n2d7
bool Genealogy::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
    Q_UNUSED(eventType)

    //最大化情况下禁止拖动
    if(this->window()->geometry() == this->window()->screen()->availableGeometry()){
        return QWidget::nativeEvent(eventType, message, result);
    }

    //窗体边框设置为2
    int border = 2;
    MSG *param = static_cast<MSG *>(message);

    if (param->message == WM_NCHITTEST)
    {
        int nX = GET_X_LPARAM(param->lParam) - this->geometry().x();
        int nY = GET_Y_LPARAM(param->lParam) - this->geometry().y();

        // 如果鼠标位于子控件上，则不进行处理
        if (childAt(nX, nY) != nullptr){
            return QWidget::nativeEvent(eventType, message, result);
        }

        *result = HTCAPTION;

        // 鼠标区域位于窗体边框，进行缩放，窗体边框设置为2
        if ((nX > 0) && (nX < border))
            *result = HTLEFT;

        if ((nX > this->width() - border) && (nX < this->width()))
            *result = HTRIGHT;

        if ((nY > 0) && (nY < border))
            *result = HTTOP;

        if ((nY > this->height() - border) && (nY < this->height()))
            *result = HTBOTTOM;

        if ((nX > 0) && (nX < border) && (nY > 0)
                && (nY < border))
            *result = HTTOPLEFT;

        if ((nX > this->width() - border) && (nX < this->width())
                && (nY > 0) && (nY < border))
            *result = HTTOPRIGHT;

        if ((nX > 0) && (nX < border)
                && (nY > this->height() - border) && (nY < this->height()))
            *result = HTBOTTOMLEFT;

        if ((nX > this->width() - border) && (nX < this->width())
                && (nY > this->height() - border) && (nY < this->height()))
            *result = HTBOTTOMRIGHT;

        return true;
    }
    return QWidget::nativeEvent(eventType, message, result);
}

//更新全局主题，原理是利用QString的replace方法
//改变颜色，实现更改颜色主题的功能
void Genealogy::updateTheme(int newTheme){
    QString stylesheet = styleSheet();
    stylesheet.replace(themeColors[themeIndex].name().remove("#"),
                       themeColors[newTheme].name().remove("#"));
    setStyleSheet(stylesheet);
    menuBar->updateTheme(themeColors[newTheme], themeColors[themeIndex]);
    toolWidget->updateTheme(themeColors[newTheme], themeColors[themeIndex]);
    displayWidget->updateTheme(themeColors[newTheme], themeColors[themeIndex]);
    themeIndex = newTheme;
    qDebug()<<"themeIndex"<<themeIndex;
}

//打开新的文件
void Genealogy::openFile(){
    QString filePath = QFileDialog::getOpenFileName(
                this,
                tr("打开家谱文件"),
                "C:/",
                tr("家谱文件(*.ft)"));
    if(!filePath.isEmpty()){

        //将打开文件的文件名加入标题栏中显示
        titleBar->setTitle("家谱管理器-"+filePath.split('/').last());

        //如果有已经打开大文件
        //先关闭当前文件
        if(isFileOpening){
            closeFile();
        }
        if(!treeData.inputDataFromFile(filePath)){
            displayWidget->setCurrentIndex(3);
        }
        else{
            displayWidget->inputDataToTableWidget();
            displayWidget->inputDataToTreeWidget();
        }
        menuBar->enableDisplayMenu();
        isFileOpening = true;
        curFilePath = filePath;
    }
}

//新建文件，获得新建文件的路径与名字
void Genealogy::newFile(){
    QString filePath = QFileDialog::getSaveFileName(
                this,
                tr("新建家谱文件"),
                "C:/",
                tr("家谱文件(*.ft)"));
    if(!filePath.isEmpty()){
        if(isFileOpening){
            closeFile();
        }
        treeData.inputDataFromFile(filePath);
        titleBar->setTitle("家谱管理器-"+filePath.split('/').last());
        displayWidget->setCurrentIndex(3);
        isFileOpening = true;
        curFilePath = filePath;
    }
}

//关闭文件
void Genealogy::closeFile(){

    //关闭文件的时候，输出数据
    treeData.outputDataToFile(curFilePath);

    //刷新控件
    treeData.clear();
    displayWidget->clear();
    displayWidget->setCurrentIndex(2);
    if(!toolWidget->isHidden()){
        closeToolAreaAnima();
    }
    isFileOpening = false;
    titleBar->setTitle("家谱管理器");
}

//重载Qt的关闭事件，完成一些数据导出的操作
void Genealogy::closeEvent(QCloseEvent *event){
    if(isFileOpening){
        closeFile();
    }
    QFile file(QApplication::applicationDirPath()+"/theme");
    if(file.open(QIODevice::WriteOnly | QIODevice::Text| QIODevice::Truncate)){
        QTextStream stream(&file);
        stream<<themeIndex<<endl;
    }
    file.close();
    event->accept();
}




